import 'package:flutter/material.dart';
import 'package:flutter_applearnprogrom/utils/viewutils/TextFieldWidget.dart';
import 'package:flutter_swiper/flutter_swiper.dart';
import 'package:english_words/english_words.dart';

final List<String> items = [];
List<IconData> _icons = []; //保存Icon数据
 const loadingTag = "##loading##"; //表尾标记
var _words = <String>[loadingTag];
class HomePage extends StatefulWidget {

  @override
  State<StatefulWidget> createState() {
    return _IndexState();
  }
}

class _IndexState extends State<HomePage> {
  @override
  void initState() {
    super.initState();
    _retrieveIcons();
    _retrieveData();
    for (int i = 0; i < 10; i++) {
      items.add("temi");
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
//      appBar: new AppBar(
//        title:  TextFieldWidget(),
//        backgroundColor: Colors.green,
//      ),
      body: buildGridView1(),
    );
  }

  Widget buildGridView1() {
    TextEditingController _pass;
    return Column(

        //测试Row对齐方式，排除Column默认居中对齐的干扰
        crossAxisAlignment: CrossAxisAlignment.start,
        children: <Widget>[
          Column(
            mainAxisAlignment: MainAxisAlignment.center,
            children: <Widget>[
              TextFieldWidget(),
            ],
          ),
          Column(children: <Widget>[
//            buildGridView(),
            new Container(
              width: MediaQuery.of(context).size.width,
              height: 200,
              child: Swiper(
                  itemCount: 2,
                  itemBuilder: _swiperBuilder,
                  pagination: new SwiperPagination(
                      builder: DotSwiperPaginationBuilder(
                    color: Colors.black54,
                    activeColor: Colors.white,
                    size: 5.0,
                    activeSize: 5.0,
                  )),
                  scrollDirection: Axis.horizontal,
                  autoplay: true,
                  onTap: (index) => print('点击了第$index个')),
            ),
          ]),
          Divider(height: 20),
          Column(
            children: <Widget>[
//            buildGridView(),
              new Container(
                width: MediaQuery.of(context).size.width,
                height: 70,
//                child: buildGridView(),

                child:   GridView.builder(
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                    crossAxisCount: 3, //每行三列
                    childAspectRatio: 1.0, //显示区域宽高相等
                  ),
                  itemCount: _icons.length,
                  itemBuilder: (context, index) {
                    //如果显示到最后一个并且Icon总数小于200时继续获取数据
                    if (index == _icons.length - 1 && _icons.length < 200) {
                      _retrieveIcons();
                    }
                    return Icon(_icons[index]);
                  },
                ),
              )
            ],
          ),
          Divider(height: 20),
          Column(
            children: <Widget>[
//            buildGridView(),
              new Container(
                width: MediaQuery.of(context).size.width,
                height: 70,
//                child: buildGridView(),

                child:   ListView.separated(
                  itemCount: _words.length,
                  itemBuilder: (context, index) {
                    //如果到了表尾
                    if (_words[index] == loadingTag) {
                      //不足100条，继续获取数据
                      if (_words.length - 1 < 100) {
                        //获取数据
                        _retrieveData();
                        //加载时显示loading
                        return Container(
                          padding: const EdgeInsets.all(16.0),
                          alignment: Alignment.center,
                          child: SizedBox(
                            width: 24.0,
                            height: 100.0,
                            child: CircularProgressIndicator(strokeWidth: 2.0),
                          ),
                        );
                      } else {
                        //已经加载了100条数据，不再获取数据。
                        return Container(
                          alignment: Alignment.center,
                          padding: EdgeInsets.all(16.0),
                          child: Text(
                            "没有更多了",
                            style: TextStyle(color: Colors.grey),
                          ),
                        );
                      }
                    }
                    //显示单词列表项
                    return ListTile(title: Text(_words[index]));
                  },
                  separatorBuilder: (context, index) => Divider(height: .0),
                ),
              )
            ],
          ),

        ]);
  }

  ///GridView 的基本使用
  ///通过custom方式来创建
  Widget buildGridView() {
    return GridView.custom(
        cacheExtent: 200,

        ///子Item排列规则
        gridDelegate: SliverGridDelegateWithMaxCrossAxisExtent(
          ///子Item的最大宽度
          maxCrossAxisExtent: 100,
          //纵轴间距
          mainAxisSpacing: 10.0,
          //横轴间距
          crossAxisSpacing: 10.0,
          //子组件宽高长度比例
          childAspectRatio: 1.4,
        ),

        ///子条目的构建模式
        childrenDelegate:

            ///懒加载的模式
            SliverChildBuilderDelegate((BuildContext context, int index) {
          return buildListViewItemWidget(index);
        }));
  }

  List<Widget> buildListViewItemList() {
    List<Widget> list = [];

    ///模拟的8条数据
    for (int i = 4; i < 0; i--) {
      list.clear();
      list.add(buildListViewItemWidget(i));
    }
    list.clear();
    return list;
  }

  ///创建GridView使用的子布局
  Widget buildListViewItemWidget(int index) {
    return new Container(

        ///内容剧中
        alignment: Alignment.center,

        ///根据角标来动态计算生成不同的背景颜色
        color: Colors.cyan[100 * (index % 9)],
//      child: new Image.asset(name),

        child:
//      new Text('grid item $index'),

            Column(children: <Widget>[
          new Image(
            image: new NetworkImage(
                "https://2a.zol-img.com.cn/product/124_501x2000/746/cexItD2yJ21Rs.jpg"),
            width: 20,
            height: 40,
            fit: BoxFit.cover,
          ),
          new Text('grid item $index'),
        ]));
  }

  Widget _swiperBuilder(BuildContext context, int index) {
    return (Image.network("http://via.placeholder.com/350x150",
        fit: BoxFit.fill));
  }

  //模拟异步获取数据
  void _retrieveIcons() {
    Future.delayed(Duration(milliseconds: 200)).then((e) {
      setState(() {
        _icons.addAll([
          Icons.ac_unit,
          Icons.airport_shuttle,
          Icons.all_inclusive,
          Icons.beach_access,
          Icons.cake,
          Icons.free_breakfast,
        ]);
      });
    });
  }


//  ListView shuju
  void _retrieveData() {
    Future.delayed(Duration(seconds: 2)).then((e) {
      setState(() {
        //重新构建列表
        _words.insertAll(
          _words.length - 1,
          //每次生成20个单词
          generateWordPairs().take(20).map((e) => e.asPascalCase).toList(),
        );
      });
    });
  }

}
